package com.upcode.weighing.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.upcode.weighing.domain.SysEmp;
import com.upcode.weighing.domain.SysOrganization;
import com.upcode.weighing.mapper.SysOrganizationMapper;
import com.upcode.weighing.service.SysOrganizationService;
import com.upcode.weighing.util.SecurityUtils;
import com.upcode.weighing.util.SensitiveInfoUtils;
import com.upcode.weighing.vo.req.PageReqVo;
import com.upcode.weighing.vo.resp.PageRespVo;
import com.upcode.weighing.vo.resp.org.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.upcode.weighing.common.constant.BillConstants.SEX_NAN;

/**
 * <p>
 * 组织机构管理 服务实现类
 * </p>
 *
 * @author zhangteng
 * @since 2021-01-14
 */
@Service
public class SysOrganizationServiceImpl extends ServiceImpl<SysOrganizationMapper, SysOrganization> implements SysOrganizationService {
    private static final Logger logger = LoggerFactory.getLogger(SysOrganizationServiceImpl.class);

    @Autowired
    private SysOrganizationMapper sysOrganizationMapper;


    //添加机构
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int addOrganization(OrgAddVo vo) {
        SysOrganization o=new SysOrganization();
        o.setId(IdWorker.getId());//机构id
        o.setCode(this.getOrgCode(vo.getAdd()));//机构编码
        o.setPid(vo.getPid());//机构父级id
        o.setName(vo.getName());//机构/部门/岗位名称
        o.setType(vo.getType());//机构类型 1机构 2部门 3岗位
        o.setAddress(vo.getAddress());//机构所在地-详细地址
        o.setDelStatus(1);//删除状态 0已删除  1未删除 默认为1
        o.setStatus(1);//机构状态 0已禁用  1开启 默认为开启
        o.setLinkName(vo.getLinkName());//负责人
        o.setLinkPhone(vo.getLinkPhone());//负责人联系电话
        o.setRoomPhone(vo.getRoomPhone());//负责人办公座机电话
        o.setDes(vo.getDes());//备注
        o.setCreateUserId(SecurityUtils.getCurrentUserId());//添加人id
        o.setCreateTime(LocalDateTime.now());//添加时间
        o.setLastUpdateUserId(SecurityUtils.getCurrentUserId());//最后修改人id
        o.setLastUpdateTime(LocalDateTime.now());//最后修时间
        return sysOrganizationMapper.addOrganization(o);
    }

    //查询机构编码是否存在
    @Override
    public int getOrganizationByCode(String orgCode) {
        return sysOrganizationMapper.getOrganizationByCode(orgCode);
    }

    //获取所有组织机构
    @Override
    public List<SysOrganization> getOrganizationList() {
        List<SysOrganization> list=sysOrganizationMapper.getOrganizationList();
        List<SysOrganization> list1=new ArrayList<SysOrganization>();
        for(SysOrganization r:list){
            if(r.getPid()==0){
                list1.add(r);
            }
        }
        for(SysOrganization r:list1){
            r.setChildOrganization(getChild(r.getId(),list));
        }
        return list1;
    }

    //添加组织-用户信息
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int addEmp(SysEmpAddVo vo) {
        SysEmp s=new SysEmp();
        s.setId(IdWorker.getId());//员工ID
        s.setName(vo.getName());//员工姓名
        s.setUserCode(vo.getUserCode());//员工编码
        s.setOrgId1(vo.getOrgId1());//所在公司ID
        s.setOrgId2(vo.getOrgId2());//所在部门ID
        s.setOrgId3(vo.getOrgId3());//所在岗位ID
        if(vo.getSex()!=null){//性别 0:女  1:男
            s.setSex(vo.getSex());
        }else{
            s.setSex(SEX_NAN);//默认性别为 男
        }
        s.setCard(vo.getCard());//身份证号
        s.setMobile(vo.getMobile());//电话
        s.setEmail(vo.getEmail());//邮箱
        s.setLinkName(vo.getLinkName());//紧急联系人
        s.setLinkMobile(vo.getLinkMobile());//紧急联系人手机号
        s.setImg1(vo.getImg1());//电子照片
        s.setImg2(vo.getImg2());//证书照片,多个用逗号隔开
        s.setCreateTime(LocalDateTime.now());//创建时间
        s.setCreateUserId(SecurityUtils.getCurrentUserId());//创建人ID
        s.setUpdateTime(LocalDateTime.now());//修改时间
        s.setUpdateUserId(SecurityUtils.getCurrentUserId());//修改人ID
        //将员工信息添加到sys_user
        Map m=new HashMap();
        m.put("id", IdWorker.getId());//id
        m.put("login_name",s.getUserCode());//登录名 员工工号
        m.put("pwd",new BCryptPasswordEncoder().encode("123456"));//密码 默认为123456
        m.put("name",s.getName());//姓名
        m.put("email",s.getEmail());//邮箱
        m.put("sex",s.getSex());//性别
        m.put("telephone",s.getMobile());//手机号
        m.put("card",s.getCard());//身份证号
        m.put("status",0);//可用状态  默认为不可用 0
        m.put("create_time",s.getCreateTime());//创建时间
        m.put("organ_id1",s.getOrgId1());//公司id
        m.put("organ_id2",s.getOrgId2());//部门id
        m.put("organ_id3",s.getOrgId3());//岗位id
        if (vo.getWorkOrderAuth() == null){
            vo.setWorkOrderAuth(0);
        }
        m.put("work_order_auth", vo.getWorkOrderAuth()); // added by leidong 工单系统使用字段
        sysOrganizationMapper.addEmpToSysUser(m);
        return sysOrganizationMapper.addEmp(s);
    }

    //判断员工编码是否存在
    @Override
    public int checkEmp(String userCode) {
        return sysOrganizationMapper.checkEmp(userCode);
    }

    //获取所有公司信息列表
    @Override
    public List<SysOrganization> getOrgCompany() {
        return sysOrganizationMapper.getOrgCompany();
    }

    //根据公司ID获取部门列表
    @Override
    public List<SysOrganization> getOrgDept(Long id) {
        return sysOrganizationMapper.getOrgDept(id);
    }

    //根据部门ID获取岗位列表
    @Override
    public List<SysOrganization> getOrgGw(Long id) {
        return sysOrganizationMapper.getOrgGw(id);
    }

    //组织用户分页列表
    @Override
    public PageRespVo<OrgEmpPageListVo> selectPageList(PageReqVo<OrgEmpPageListVo> vo) {
        Page<OrgEmpPageListVo> pageInfo = new Page<>(vo.getPage().getCurrentPage(), vo.getPage().getPageSize());//创建分页
        PageRespVo<OrgEmpPageListVo> pageRespVo = new PageRespVo<OrgEmpPageListVo>();
        IPage<OrgEmpPageListVo> iPage = sysOrganizationMapper.selectPageList(pageInfo,vo.getParams());
        pageRespVo.setPage(iPage);
        for(OrgEmpPageListVo ov:pageRespVo.getPage().getRecords()){
            ov.setCard(SensitiveInfoUtils.sensitiveIdCard(ov.getCard()));//身份号
            ov.setMobile(SensitiveInfoUtils.sensitiveTel(ov.getMobile()));//手机号
            ov.setLinkMobile(SensitiveInfoUtils.sensitiveTel(ov.getLinkMobile()));//紧急联系人
        }
        return pageRespVo;
    }

    //批量删除组织
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int delOrg(OrgDelVo vo) {
        return sysOrganizationMapper.delOrg(vo.getId());
    }

    //修改组织
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int upOrgName(OrgEditVo vo) {
        SysOrganization s=new SysOrganization();
        s.setId(vo.getId());//修改的ID
        s.setName(vo.getName());//修改的名字
        s.setLastUpdateUserId(SecurityUtils.getCurrentUserId());//最后修改人ID
        s.setLastUpdateTime(LocalDateTime.now());//最后修改时间
        return sysOrganizationMapper.upOrgName(s);
    }

    //判断添加的节点是第几级节点
    @Override
    public Long checkType(Long oId) {
        return sysOrganizationMapper.checkType(oId);
    }

    //修改员工信息
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int upEmp(SysEmpEditVo vo) {
        SysEmp s=new SysEmp();
        s.setId(vo.getId());//员工id
        s.setName(vo.getName());//姓名
        s.setOrgId1(vo.getOrgId1());//公司
        s.setOrgId2(vo.getOrgId2());//部门
        s.setOrgId3(vo.getOrgId3());//岗位
        boolean contains = vo.getCard().contains("*");
        s.setCard(vo.getCard());//身份证号
        if (contains){
            s.setCard("");//身份证号
        }
        boolean contains1 = vo.getMobile().contains("*");
        s.setMobile(vo.getMobile());//电话
        if (contains1){
            s.setMobile("");//电话
        }
        s.setEmail(vo.getEmail());//邮箱
        s.setLinkName(vo.getLinkName());//紧急联系人
        boolean contains2 = vo.getLinkMobile().contains("*");
        s.setLinkMobile(vo.getLinkMobile());//紧急联系人手机号
        if (contains2){
            s.setLinkMobile("");//紧急联系人手机号
        }
        s.setImg1(vo.getImg1());//电子照片
        s.setImg2(vo.getImg2());//证书
        s.setUpdateTime(LocalDateTime.now());//修改时间
        s.setUpdateUserId(SecurityUtils.getCurrentUserId());//修改人ID
        return sysOrganizationMapper.upEmp(s);
    }

    //删除员工
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int delEmp(SysEmpDelVo vo) {
        return sysOrganizationMapper.delEmp(vo.getIds());
    }

    //根据ID获取员工信息
    @Override
    public SysEmp getEmpById(SysEmpDelVo vo) {
        return sysOrganizationMapper.getEmpById(vo.getId());
    }

    //解除组织与员工的绑定
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int delOrgEmp(OrgDelVo vo) {
        return sysOrganizationMapper.delOrgEmp(vo.getId());
    }

    //解除组织与用户的绑定
    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int delOrgUser(OrgDelVo vo) {
        return sysOrganizationMapper.delOrgUser(vo.getId());
    }

    @Override
    public List<String> getEmpName(Long[] ids) {
        return sysOrganizationMapper.getEmpName(ids);
    }

    @Transactional(readOnly = false,rollbackFor = Exception.class)
    @Override
    public int delEmpAndUser(String[] loginName) {
        return sysOrganizationMapper.delEmpAndUser(loginName);
    }

    //递归查找子菜单
    private List<SysOrganization> getChild(Long id,List<SysOrganization> list){
        List<SysOrganization> childList = new ArrayList<SysOrganization>();
        for(SysOrganization r:list){
            if(r.getPid().equals(id)){
                childList.add(r);
            }
        }
        for(SysOrganization r:childList){
            r.setChildOrganization(getChild(r.getId(),list));
        }
        if(childList.size()==0){
            return null;
        }
        return childList;
    }

    public String getOrgCode(Integer type){
        Integer orgType=null;
        if(type==0){
            orgType=type+1;
        }else if(type==1){
            orgType=type+1;
        }else if(type==2){
            orgType=type+1;
        }
        List<String> res=sysOrganizationMapper.getCode(orgType);
        List<Integer> convertList=new ArrayList<>();
        res.forEach(item->{
            convertList.add(Integer.parseInt(item));
        });
        Integer code= CollectionUtil.max(convertList)+1;
        return code.toString();
    }
}
